/*
* $Id: PrimeNumber.java 70 2012-12-11 12:04:18Z Denis.Skalsky@gmail.com $
*/
package com.globallogic.skalskyy.javabasic.primenumber;

import com.globallogic.skalskyy.javabasic.inputdata.ConsoleReader;
import com.globallogic.skalskyy.javabasic.inputdata.DataValidator;

/**
* PrimeNumber finds primenumber.
* @author $Author: denis.skalsky@gmail.com $
* @version $Revision: 40 $
*/
public class PrimeNumber {
	
	private static final String CLOSE_BRACKET = "]";
	private static final String RESULT_SEPARATOR = ", ";
	private static final String OPEN_BRACKET = "[";
	private static final String EMPTY_RESULT = "[]";
	/** Getting inputted data. */
	private DataValidator dataValidator = new DataValidator();
	
	public void setConsoleReader() {
		this.dataValidator.setIncomingData(
				new ConsoleReader(ConsoleReader.ConsoleCommandPrompt.PRIME));
	}
	
	/** Get inputted max prime number */
	public int getMaxPrimeNumber () {
		return dataValidator.getIntPositiveValue();
	}

	/**
	* Find primenumbers using sieve of Eratosthenes.
	* @param input max number to narrow the list of primenumber
	* @return result string
	*/
	public String findUsingSieveOfEratosthenes(int input) {
		if ((input == 0) || (input == 1)) {
			return EMPTY_RESULT;
		}
		
		int [] arrayPrimes = new int[input];		
		for (int i = 0; i < input; i++) {
			arrayPrimes[i] = i + 1;			
		};
		
		arrayPrimes[0] = 0;			
		for (int i = 1; (i + 1) * (i + 1) <= input; i++) {
			if (arrayPrimes[i] > 0) {			
				for (int j = 2 * i + 1; j < input; j += i + 1) {
					arrayPrimes[j] = 0;
				};
			};
		};
		
		StringBuilder result = new StringBuilder();
		result.append(OPEN_BRACKET);
		for (int i = 0; i < input; i++) {		
			if (arrayPrimes[i] != 0) {
				result.append(arrayPrimes[i]);
				result.append(RESULT_SEPARATOR);
			};
		};
		result.replace(result.length() - 2, result.length(), CLOSE_BRACKET);
		
		return result.toString();
	}
	
	/**
	* Find primenumbers using nested loops.
	* @param input max number to narrow the list of primenumber
	* @return result string
	 */
	public String findUsingNestedLoops(int input) {
		if ((input == 0) || (input == 1)) {
			return EMPTY_RESULT;
		}
		
		StringBuilder result = new StringBuilder();
		result.append(OPEN_BRACKET);		
		int primeNumber;
	 	for (int i = 2; i <= input; i++) {
		    primeNumber = i;
			for (int j = 2; j < primeNumber; j++) {			    
				if ((primeNumber % j) == 0) {
				    primeNumber = 0;
					break;
				}
			}
			if (primeNumber > 0) {
				result.append(primeNumber);
				result.append(RESULT_SEPARATOR);
			}
		}		
		result.replace(result.length() - 2, result.length(), CLOSE_BRACKET);
		
		return result.toString();
	}
}